var current_lang = '';
var current_page = 0;
var firstQBLoad = false;

$(document).ready(function(){
	firstLoad = true;
	//if args is sent get questions
	var vars = $.getUrlVars();
	var s = vars['s'];
	var lang = vars['lang'];
	var series = vars['series'];	
        
        $(".heading").click(function(){
		$(this).next(".content").slideToggle(500);	
		$(this).toggleClass('header-open');
	});
        $(".content").hide();
});

function buildPager(number_of_hits){	
    if(number_of_hits > items_per_page){
            $("#qb-pagination").show();
            $("#qb-pagination").pagination(number_of_hits, {
                    items_per_page:items_per_page, 
                    callback:handlePaginationClick,
                    next_text: 'Next',
                    prev_text: 'Prev',
                    link_to:"#",
                    num_edge_entries:2,
                    ellipse_text: '..'
            });
    }else{
            $("#qb-pagination").hide();
    }
    firstQBLoad = false;
}

function handlePaginationClick(new_page_index, pagination_container) {	
    if(new_page_index != current_page){
        var s           = $('input[name=s]').val();

        var start 	= new_page_index*items_per_page;
        var end 	= (start + items_per_page);

        current_page = new_page_index;
        searchQB(s,start,items_per_page);
    }
	
    return false;
}

function searchQB(s, start,records){
	if(s != ''){                
                var data = {
                    s:s, 
                    start:start, 
                    records:records
                };

		var lang = $("#select-language").val();
                if(lang != 'all')
                    data['lang'] = lang;
                
                if($("#series").val())
                    data['series'] = $("#series").val().join(',');


		if(current_lang.length != 0){
			data.lang = current_lang;
		}
		$.ajax({
                    url: backend+'/db/ddi/ws/qb/qb-json.xql',
                    dataType: 'json',
                    data: data,
                    success: searchDone
		});
                $('.question-tab').toggleClass('loading');
	}else{
		$("#qb-hits-count").html('');
		$("#qb-result").html('');
		$("#qb-pagination").hide();		
	}
}

function searchDone(data){
	if(parseInt(data.hits) > 0){
		$("#qb-hits").html((parseInt(data.start)+1)+'-'+(parseInt(data.end))+' of '+' '+(data.hits));	
		$("#qb-hits-count").html('('+data.hits+')');
		$("#qb-pagination").show();
	
	
                console.log('results: '+data.hits);
                console.log('array: '+(data.questions['QuestionItem'] instanceof Array));

                var output = '';
                if(data.questions['QuestionItem'] instanceof Array){

                    $.each(data.questions['QuestionItem'], function(i,questionItem){
                        console.log('loop ' + i);
                        output +=  renderQuestion(questionItem);
                    });
                }else{
                    output +=  renderQuestion(data.questions['QuestionItem']);
                }
                $("#qb-result").html(output);

                //$(".question-block p").hide();
                //$(".question-block ."+$("#select-language").val()).show();

                $('.question-info').click(function(e){
                        e.preventDefault();

                        var qid = $(this).attr("id");

                        qid = qid.replace('question-info-expand-','');
                        $(this).addClass('question-info-loading');
                        $.ajax({
                                url: backend+'/db/ddi/ws/qb/qb-get-study-units.xql',
                                dataType: 'json',
                                data: {
                                        qid:qid
                                },
                                success: loadedQuestionInfo
                        });
                });
    	}else{
		$("#qb-hits-count").html('');
		$("#qb-result").html('');
		$("#qb-pagination").hide();
	}
        
        //if this is the first result-set
        if(firstQBLoad || data.hits < items_per_page){
           buildPager(data.hits);
        }
        $('.question-tab').toggleClass('loading');
}

function renderQuestion(questionItem){
    var output = '';
    var qid = questionItem.id;
    var question_id = questionItem.id; 
    
    if(questionItem['UserID'] instanceof Array)
        question_id = questionItem.UserID[0]['#text'];
    else if(questionItem['UserID']['#text'])
        question_id = questionItem.UserID['#text'];
    
    output += '<div id="'+qid+'" class="question-block">';
    if(questionItem['QuestionText'].length > 1){
            $.each(questionItem['QuestionText'], function(i,questionText){
                    output += '<p class="'+questionText['xml:lang']+'"><img src="img/lang/'+questionText['xml:lang']+'.gif" />';
                    output += questionText['LiteralText']['Text'];
                    output += '</p>';
            });
    }else{
            output += '<p class="'+questionItem['QuestionText']['xml:lang']+'"><img src="img/lang/'+questionItem['QuestionText']['xml:lang']+'.gif" />';
            output += questionItem['QuestionText']['LiteralText']['Text'];
            output += '</p>';
    }

    output += '<div id="question-info-'+question_id+'"></div><a id="question-info-expand-'+question_id+'" href="#" class="question-info">show studies</a></div>';

    return output;
}


function loadedQuestionInfo(data){
	$("#question-info-expand-"+data['question-id']).removeClass('question-info-loading');
	$("#question-info-"+data['question-id']).hide(0);
	var output = '<ul class="question-in-studies-list">';
	if('study' in data){	
		if(data['study'].length > 1){
			$.each(data['study'], function(i,study){
				output += renderStudyLink(study);
			});
		}else{
			output += renderStudyLink(data.study);
		}
		output += '</ul>';
		$("#question-info-"+data['question-id']).html(output);
		$("#question-info-expand-"+data['question-id']).hide(0);
		$("#question-info-"+data['question-id']).show("fast", "linear");
	}else{
		$("#question-info-expand-"+data['question-id']).html('no studies found');
	}
	
	function renderStudyLink(study){
		var lang_arg='';
		if(current_lang.length != 0){
			lang_arg='&lang='+current_lang;
		}
		var output = '<li>'+study['questionItemName']['en']+' <a target="_blank" href="http://bull.ssd.gu.se:8080/exist/rest/db/ddi/ws/export/study-xhtml.xql?id='+study['studyId']+lang_arg+'#question-'+data['question-id']+'">'+study['title']['en']+'</a></li>';
		return output;
	}
}

/*******************************************************************************/
// Read a page's GET URL variables and return them as an associative array.
$.extend({
	getUrlVars: function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++){
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});
